package touchpad;

import it.mouseclient.UDPClient;

import java.util.Timer;
import java.util.TimerTask;

import android.graphics.Point;
import android.view.MotionEvent;

import common.CommandType;

public class RightClick extends TouchpadCommand {


	private static final long DELAY_WAIT_CLICK = 800;

	// quadrato della tolleranza in pixel
	private static final int TOLERANCE = 25;
	private Timer timerRightClick;
	private boolean sendRightClick;

	private Point finger1, finger2;

	public RightClick(UDPClient client) {
		super(client);
		sendRightClick = false;
		timerRightClick = new Timer();
		finger1 = new Point();
		finger2 = new Point();
	}

	@Override
	public boolean onUpTouch(MotionEvent m) {
		boolean success=true;
		stopTimer();

		if (getSendRightClick()) {
			if (client != null) {
				
				success=client.executeCommand(CommandType.RIGHT_CLICK, null);
			}

		}
		setSendRightClick(false);
		return success;
	}

	@Override
	public boolean onDownTouch(MotionEvent m) {
		return true;

	}

	@Override
	public boolean onMoveTouch(MotionEvent m) {
		
		if (m.getPointerCount() == 2 && !checkMultitouchMovement(m)) {
			stopTimer();
			setSendRightClick(false);
		}
		return true;

	}

	@Override
	public boolean onDownMultitouch(MotionEvent m) {

		if (m.getPointerCount() == 2) {

			TouchUtilities.getFingersPoint(m, finger1, finger2);

			
			setSendRightClick(true);
			timerRightClick.schedule(new TimerTask() {

				@Override
				public void run() {
					setSendRightClick(false);
					
				}
			}, DELAY_WAIT_CLICK);
		} else {
			setSendRightClick(false);
			stopTimer();
			
		}
		return true;

	}

	@Override
	public boolean onUpMultitouch(MotionEvent m) {
		return true;
	

	}

	private synchronized void setSendRightClick(boolean send) {
		this.sendRightClick = send;
		
	}

	private synchronized boolean getSendRightClick() {
		return this.sendRightClick;

	}

	private void stopTimer() {
		timerRightClick.cancel();
		timerRightClick = new Timer();
	}



	private boolean checkMultitouchMovement(MotionEvent m) {
		Point f1 = new Point();
		Point f2 = new Point();
		TouchUtilities.getFingersPoint(m, f1, f2);
		int dx1_square = (int) Math.pow(finger1.x - f1.x, 2);
		int dy1_square = (int) Math.pow(finger1.y - f1.y, 2);
		int dx2_square = (int) Math.pow(finger2.x - f2.x, 2);
		int dy2_square = (int) Math.pow(finger2.y - f2.y, 2);

		if ((dx1_square + dy1_square) <= TOLERANCE
				&& (dx2_square + dy2_square) <= TOLERANCE)
			return true;
		else
			return false;

	}

}
